/*
 * FriendshipBoxResource.cpp
 *
 *  Created on: 2013. 9. 6.
 *      Author: mega@gamevil.com
 */

#include "../User.h"
#include "FriendshipBoxResource.h"
#include <Database/Static.h>
#include "../NUtil/Pool.h"
#include "../NUtil/Utils.h"

namespace ProjectZ { namespace NResource {

FriendshipBoxResource::FriendshipBoxResource()
{
	pFriendshipBoxAndroid	= new FriendshipBoxData;
	pFriendshipBoxIOS		= new FriendshipBoxData;
}

FriendshipBoxResource::~FriendshipBoxResource()
{
	delete pFriendshipBoxAndroid;
	delete pFriendshipBoxIOS;
}

bool FriendshipBoxResource::LoadResource()
{
	if ( false == pFriendshipBoxAndroid->LoadResource(MARKET_GOOGLE, SC_KAKAO_GOOGLE) )
		return false;

	if ( false == pFriendshipBoxIOS->LoadResource(MARKET_IOS, SC_KAKAO_IOS) )
		return false;

	return true;
}

FriendshipBoxData * FriendshipBoxResource::GetFly(User * pUser)
{
	NUtil::MarketType marketType = NUtil::GetMarketType(pUser->GetCompany(), pUser->GetSaleCode());

	switch (marketType)
	{
	case NUtil::MarketType::AD_KAKAO:
		return pFriendshipBoxAndroid;

	case NUtil::MarketType::IOS_KAKAO:
		return pFriendshipBoxIOS;

	default:
		return NULL;
	}

	return NULL;
}

FriendshipBoxData::~FriendshipBoxData()
{
	std::for_each(_clsFlyTree.begin(), _clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<DATATREE::value_type>);
}

void
FriendshipBoxData::Clear()
{
	std::for_each(_clsFlyTree.begin(), _clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<DATATREE::value_type>);
	_clsFlyTree.clear();
	_totalRate = 0;
}

bool FriendshipBoxData::LoadResource(int company, int saleCode)
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT * FROM resource_friendship_box_reward WHERE company=%d AND sale_cd=%d", company, saleCode);

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	int seq, tmpCompany, tmpSaleCode;
	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		FriendshipBoxData::Flyweight * pFly = new FriendshipBoxData::Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> seq >> tmpCompany >> tmpSaleCode >> pFly->_ITEM_NAME
				>> pFly->_SHEET_TYPE >> pFly->_REWARD_TID >> pFly->_COUNT >> pFly->_RATE;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		_clsFlyTree[seq] = pFly;
		_totalRate += pFly->_RATE;
	}

	return true;
}

} /* NResource */ } /* ProjectZ */
